import React, { useEffect, useReducer } from "react";

function reducer(state, action) {
  //state表示数据(状态)  action 描述的对象
  switch (action.type) {
    case "init":
        return action.payload;
    case "add":
      return [...state, action.payload];
    case  "del":
        return  state.filter(item=>item.id!==action.payload)  
    default:
      return state;
  }
}

export default function UseReducer() {
  const [state, dispatch] = useReducer(reducer, []);

  useEffect(() => { //页面加载成功

        dispatch({
            type:"init",
            payload:[{id:1},{id:2},{id:3}]
        })
  
  }, [])
  

  //     const [list, setlist] = useState([]);
  //     //新增数据
  //    // setlist([...list,item])
  //    // setlist(list.filter(item=>item.id!==id));
  //    // setlist(list.map(item=>{
  //    //  if(item.id ===id){ item.name="abc"}
  //    //     return item
  //    //  }))

  let add = function () {
    //调用接口  成功以后同步页面效果
    dispatch({
      type: "add",
      payload: { id: 3 },
    });
  };
  let delById = (payload) => {
    dispatch({
      type: "del",
      payload,
    });
  };

  return (
    <div>
      <button onClick={add}>新增</button>
      <div className="tr">
        <div className="td">编号</div>
        <div className="td">操作</div>
      </div>
      {state.map((item) => {
        return (
          <div className="tr" key={item.id}>
            <div className="td">{item.id}</div>
            <div
              className="td"
              onClick={() => {
                delById(item.id);
              }}
            >
              删除
            </div>
          </div>
        );
      })}
    </div>
  );
}
